package com.fpx.ce.syn.jms;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueRequestor;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.FileCopyUtils;

/**
 * jms 消息发送
 * 
 * @author sunkey
 * @date Aug 28, 2013
 */
public class SynSender {

    @Test
    public void testSend() {
        // ConnectionFactory ：连接工厂，JMS 用它创建连接
        QueueConnectionFactory connectionFactory;
        // Connection ：JMS 客户端到JMS Provider 的连接
        QueueConnection connection = null;
        // Session： 一个发送或接收消息的线程
        QueueSession session;
        Queue queue;
        // TextMessage message;
        // 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD, "tcp://172.16.24.26:61616");
        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createQueueConnection();

            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createQueueSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);

            queue = session.createQueue("ecoss-test");

            QueueRequestor requestor = new QueueRequestor(session, queue);

            // 得到消息生成者【发送者】
            // 构造消息，此处写死，项目就是参数，或者方法获取
            sendOrderMessage(session, requestor);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection) {
                    connection.close();
                }
            } catch (Throwable ignore) {
            }
        }

    }

    public void sendOrderMessage(Session session, QueueRequestor requestor) throws JMSException, IOException {
        URL url = this.getClass().getResource("/epackage/GetAPACShippingLabelRequest.xml");
        File file = FileUtils.toFile(url);
        String msg = FileUtils.readFileToString(file);
        System.out.println("发送");
        TextMessage message = session.createTextMessage(msg);
//        BytesMessage response = (BytesMessage) requestor.request(message);
//        byte[] byteContent = new byte[1024];
//        int length = -1;
//        StringBuffer content = new StringBuffer();
//        while ((length = response.readBytes(byteContent)) != -1) {
//         content.append(new String(byteContent, 0, length));
//        }
//        System.out.println(content.toString());
        
        ObjectMessage response = (ObjectMessage) requestor.request(message);
        FileCopyUtils.copy((byte[])response.getObject(), new FileOutputStream("label.pdf"));
    }

    @Test
    public void send2() throws JMSException {
        QueueConnectionFactory connectionFactory;
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        MessageConsumer consumer = null;

        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD, "tcp://172.16.30.84:61616");
//        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
//                ActiveMQConnection.DEFAULT_PASSWORD, "tcp://172.16.24.26:61616");
        connection = connectionFactory.createConnection();
        connection.start();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Queue requestQueue = session.createQueue("ecoss-test");

        producer = session.createProducer(requestQueue);

        Queue responseQueue = session.createTemporaryQueue();

        producer.send(requestQueue, createRequestMessage(session, "1111111111111", responseQueue),
                DeliveryMode.PERSISTENT, 5, -1);

        consumer = session.createConsumer(responseQueue);

        TextMessage responseMessage = (TextMessage)consumer.receive(20000);
        Assert.assertNotNull(responseMessage);
        System.out.println("sender:  "+responseMessage.getText());
    }

    protected Message createRequestMessage(Session session, String obj, Destination responseQueue) throws JMSException {
        TextMessage message = session.createTextMessage();
        message.setText(obj);

        message.setJMSReplyTo(responseQueue);
        return message;
    }

}
